package com.gitee.cirnochat.common.utils;

/**
 * 兑换码工具类
 * @author FlanChan
 * @description: 用于处理兑换码相关的逻辑
 */
public final class RedeemCodeUtils {
    private RedeemCodeUtils() {
        // 私有构造函数，防止实例化
        throw new UnsupportedOperationException("RedeemCodeUtils is a utility class and cannot be instantiated");
    }

    private final static String RANDOM_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789";

    public final static String REDEEM_CODE_REGEX = "([a-z0-9]{4}-){2}[a-z0-9]{4}";

    /**
     * 验证兑换码格式是否正确
     * @param code 兑换码
     * @return 是否有效 {@link Boolean}
     */
    public static boolean isValidRedeemCode(String code) {
        if (code == null || code.isEmpty()) {
            return false;
        }
        // 格式：xxxx-xxxx-xxxx，x为小写字母或数字
        return code.matches(REDEEM_CODE_REGEX);
    }

    /**
     * 生成一个新的兑换码
     * @return 生成的兑换码 {@link String}
     */
    public static String generateRedeemCode() {
        StringBuilder code = new StringBuilder();
        int groupLength = 4;
        int groupCount = 3;
        for (int i = 0; i < groupCount; i++) {
            if (i > 0) {
                code.append("-");
            }
            for (int j = 0; j < groupLength; j++) {
                int idx = (int) (Math.random() * RANDOM_CHARS.length());
                code.append(RANDOM_CHARS.charAt(idx));
            }
        }
        return code.toString();
    }
}
